import { defineStore } from 'pinia'
import { ref } from 'vue'
import {  promotionApi } from '@/api'

export const usePromotionCodeStore = defineStore('promotionCode', () => {
  const fixAmountCodeOptions = ref<any[]>([])
  const promotionCardCodeOptions = ref<any[]>([])

  const fetchPromotionCodeOptions = async (type: number) => {
    const options = ref<any[]>([])
    if(type === 2 ){
      if(fixAmountCodeOptions.value.length>0){
        options.value = fixAmountCodeOptions.value
      }else{
        fixAmountCodeOptions.value =await getPromotionCodes(type)
        options.value = fixAmountCodeOptions.value
      }
    }else if(type === 3){
      if(promotionCardCodeOptions.value.length>0){
        options.value = promotionCardCodeOptions.value
      }else{
        promotionCardCodeOptions.value =await getPromotionCodes(type)
        options.value = promotionCardCodeOptions.value
      }
    }
    return options.value
  }
  const getPromotionCodes = async(type: number) => {
    try {
      const { data } = await promotionApi.getPromotionCodes(type)

      const processedData = data.map((item: any) => ({
        label:item.name?item.code+"("+item.name+")":item.code,
        key: item.code,
      }))
      // console.log(processedData )
      return processedData 
    } catch (error) {
      console.error('獲取優惠Code選項表失敗:', error)
    }
  }

  return {
    fixAmountCodeOptions,
    promotionCardCodeOptions,
    fetchPromotionCodeOptions,
  }
})
